/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package com.xmlutils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import com.xmlutils.utils.JsoupUtil;

/**
 * the main class of the tool
 * V1.02-20210517
 * 增加执行UiAutomator实时分析结果输出到xml的功能。
 */
public class Runner {

	public static final String WORKSPACE_DIR = System.getProperty("user.dir");                // 工作空间目录
	/**
	 * the main method will only run if it has 1 argument that is the 
	 * file name. the file name is the relative path to the file or the
	 * absolute path to the file
	 * @param args
	 * @throws IOException 
	 */
    public static void main(String[] args) {
        if (args.length == 1 && (args[0].startsWith("adb shell am instrument") || args[0].startsWith("adb -s"))) {
        	// 直接执行命令
        	File inputFile = new File(WORKSPACE_DIR + File.separator + "TestResults-All_Tests.txt");
        	String parentPath = getParentPath(inputFile);
        	String testSuite = getTestSuiteName(inputFile);
        	String outputFilePath = parentPath + File.separator + testSuite + ".xml";
        	File outputFile = createOutput(outputFilePath);
        	Converter.create(inputFile, outputFile).convertFromCmdStream(new XMLResultFormatter(), args[0]);
        	try {
				JsoupUtil.xmlToHtmlReportUseTemplateString(getHtmlTemplate(), outputFilePath, parentPath + File.separator + testSuite + ".html");
	        	System.out.println("All Done!");
			} catch (IOException e) {
				e.printStackTrace();
			}
        	
        } else if (args.length == 1) {//传进来的是文件路径，如果文件是txt，则默认转xml同时转html，如果传进来的是xml，则默认仅转html
        	try {
	        	String inputFilePath = args[0];
	        	File file  = new File(inputFilePath);
	        	System.out.println("Input file: " + file.getAbsolutePath());
	        	String fileNameStr = getTestSuiteName(file);
	        	if (inputFilePath.endsWith(".txt")) {
		        	System.out.println("start convert txt to xml");
	        		convert(inputFilePath);
		        	System.out.println("convert txt to xml done! next convert to html...");
				}
	        	System.out.println("start convert xml to html");
	        	JsoupUtil.xmlToHtmlReportUseTemplateString(getHtmlTemplate(), WORKSPACE_DIR + File.separator + fileNameStr + ".xml", WORKSPACE_DIR + File.separator + fileNameStr + ".html");
	        	System.out.println("convert xml to html done!");
	        	System.out.println("Report path: " + WORKSPACE_DIR + File.separator + fileNameStr + ".html");
	        	System.out.println("All Done!");
        	} catch (IOException e) {
        		e.printStackTrace();
        	}
        }else {
        	System.out.println("usage: <filename>");
        	System.out.println("or usage: <adb shell am instrument command to execute test>");
		}
    }
    
    /**
     * 获取html模板
     * @return
     * @throws IOException
     */
    static String getHtmlTemplate() throws IOException {
    	URL url = Runner.class.getResource("/as_template.html");  
    	InputStream in = url.openStream();
    	BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));  
    	String txt = null;
    	StringBuilder builder = new StringBuilder();
    	while((txt = reader.readLine()) != null) {  
    	    builder.append(txt + System.lineSeparator());
    	} 
    	return builder.toString();
    }

    /**
     * from the input file name, the test suite name is extracted
     * and used to create an output xml file based on the test 
     * suite name
     * @param inputFilePath
     */
    static void convert(String inputFilePath) {
        File inputFile = new File(inputFilePath);
        String parentPath = getParentPath(inputFile);
        String testSuite = getTestSuiteName(inputFile);
        String outputFilePath = parentPath + File.separator + testSuite + ".xml";
        File outputFile = createOutput(outputFilePath);
        Converter.create(inputFile, outputFile).convert();
    }
    
    /**
     * gets the parent folder from the absolute path of the file
     * @param file
     * @return
     */
    static String getParentPath(File file) {
      String filePath = file.getAbsolutePath();
      String fileName = file.getName();
      return filePath.replace(fileName, "");
   }

    /**
     * 获取测试套件名称或者不包含后缀的文件名
     * gets the test suite name or the name of the file not including the file
     * extension
     * @param file
     * @return
     */
    static String getTestSuiteName(File file) {
      String fileName = file.getName();
      return fileName.substring(0,fileName.lastIndexOf('.'));
    }

    /**
     * 如果已存在输出文件，则先清除并创建一个新的
     * if an output file exists, clear it out and create
     * a new one
     * @param outputFilePath
     * @return
     */
    static File createOutput(String outputFilePath) {
      File outputFile = new File(outputFilePath);
      if (outputFile.exists()) {
         if (!outputFile.delete()) {
            throw new RuntimeException("could not delete existing output file");
         }
      }
      try {
         if (!outputFile.createNewFile()) {
            throw new RuntimeException("could not create the new output file");
         }
      }
      catch (IOException e) {
      }
      return outputFile;
   }
}
